package com.gaofans.nrpc.client.handler;

import com.gaofans.nrpc.client.route.ServiceEvent;
import com.gaofans.nrpc.common.processor.CommonEventProcessor;
import com.gaofans.nrpc.common.processor.EventListener;
import com.gaofans.nrpc.common.processor.ServiceAuthority;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;
import java.util.Set;

/**
 * @author GaoFans
 */
@ChannelHandler.Sharable
public class CloseEventHandler extends ChannelInboundHandlerAdapter {

    private final CommonEventProcessor<ServiceEvent<ServiceAuthority>,String> processor;

    public CloseEventHandler() {
        this.processor = new CommonEventProcessor<>();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        SocketAddress address = ctx.channel().remoteAddress();
        if (address instanceof InetSocketAddress){
            InetSocketAddress addr = (InetSocketAddress) address;
            ServiceAuthority authority = new ServiceAuthority(addr.getHostString(), addr.getPort());
            Set<Map.Entry<String, EventListener<ServiceEvent<ServiceAuthority>>>> entries = processor.all().entrySet();
            for (Map.Entry<String, EventListener<ServiceEvent<ServiceAuthority>>> entry : entries) {
                entry.getValue().onDataChunk(new ServiceEvent<>(ServiceEvent.EventType.REMOVE,authority));
            }
        }
    }

    public void addListener(String listenerName, EventListener<ServiceEvent<ServiceAuthority>> listener){
        processor.register(listenerName,listener);
    }
}
